package com.waitingresult.filter;

import com.alibaba.druid.filter.FilterEventAdapter;
import com.alibaba.druid.filter.stat.StatFilterMBean;
import com.alibaba.druid.proxy.jdbc.DataSourceProxy;
import com.alibaba.druid.proxy.jdbc.JdbcParameter;
import com.alibaba.druid.proxy.jdbc.ResultSetProxy;
import com.alibaba.druid.proxy.jdbc.StatementProxy;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.regex.Pattern;

/**
 * @Author: WangShuai
 * @CreateTime: 2022-12-29  11:17
 * @Description:
 * @Version: 1.0
 */
@Slf4j
@Component
public class DemoFilter extends FilterEventAdapter  {

    private static final Pattern LINE_BREAK = Pattern.compile("\n");
    private static final Pattern BLANKS = Pattern.compile(" +");
    private static final String BLANK = " ";
    /**
     * 开启状态
     * (此注解表示此属性为nacos动态属性，对应配置中logSwitch对应的值，默认为true，且支持动态刷新)
     */
    @Value(value = "${logSwitch:true}")
    private boolean logSwitch = true;

    /**
     * 慢sql判断阈值（毫秒）
     */
    @Value(value = "${slowSqlMillis:100}")
    private long slowSqlMillis;


    @Override
    protected void statementExecuteUpdateAfter(StatementProxy statement, String sql, int updateCount) {
        internalAfterStatementExecute(statement);
    }

    @Override
    protected void statementExecuteQueryAfter(StatementProxy statement, String sql, ResultSetProxy resultSet) {
        internalAfterStatementExecute(statement);
    }

    @Override
    protected void statementExecuteQueryBefore(StatementProxy statement, String sql) {
        super.statementExecuteQueryBefore(statement, sql);
        internalAfterStatementExecute(statement);
    }

    @Override
    protected void statementExecuteBatchAfter(StatementProxy statement, int[] result) {
        internalAfterStatementExecute(statement);
    }

    @Override
    protected void statementExecuteAfter(StatementProxy statement, String sql, boolean result) {
        internalAfterStatementExecute(statement);
    }


    @Override
    public void init(DataSourceProxy dataSource) {
        System.err.println("自定义过滤器");
    }
    /**
     * 核心记录方法：判断记录慢sql
     */
    private void internalAfterStatementExecute(StatementProxy statement) {
        if (logSwitch) {
            if (statement.getSqlStat() != null) {
                long nanos = System.nanoTime() - statement.getLastExecuteStartNano();
                long millis = nanos / (1000 * 1000);
                if (millis >= slowSqlMillis) {
                    //String slowParameters = buildSlowParameters(statement);
                    String sql = statement.getLastExecuteSql();
                    sql = LINE_BREAK.matcher(sql).replaceAll(BLANK);
                    sql = BLANKS.matcher(sql).replaceAll(BLANK);

                    // 打印日志。还可自行替换为使用数据库等方式来保存，用于后续统计
                    log.warn("slow sql [" + millis + "] millis, sql: [" + sql + "], params: "
                            );
                }
            }
        }
    }
}
